﻿using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Timers;
using Eflong.DataAccess;

namespace Eflong.Monitor
{
    public class SqlBackgroudWorker //: IDisposable
    {
        public BackgroundWorker bw;

        /*
         * 保存是否释放
         */
        private bool disposed = false;
        /*
         *  系统正在运行,线程不需要退出

         */

        public bool IsRunning { get; set; }

        /*
         * 线程暂停
         */

        public bool IsSuspend { get; set; }

        public int result = 0;

        private AutoIds ids = new AutoIds( 1835000 , 1835100 , new DateTime( 2006 , 11 , 12 ) , new DateTime( 2006 , 11 , 12 ) );

        private object locker = new object( );

        private Timer timer = new Timer( 100 );

        public SqlBackgroudWorker( )
        {
            Init_bw( );
        }

        ~SqlBackgroudWorker( )
        {
            Dispose( false );
        }

        public void Dispose( )
        {
            Dispose( true );

            GC.SuppressFinalize( this );
        }

        private void Dispose( bool disposing )
        {
            if ( !this.disposed )
            {
                if ( disposing )
                {
                }
                this.IsRunning = false;

                this.disposed = true;
            }
        }

        private void Init_bw( )
        {
            bw = new BackgroundWorker( );
            bw.WorkerReportsProgress = true;

            bw.WorkerSupportsCancellation = true;

            bw.DoWork += bw_DoWork;

            bw.ProgressChanged += bw_ProgressChanged;

            bw.RunWorkerCompleted += bw_RunWorkerCompleted;

            timer = new Timer( 5000 );
            timer.Elapsed += new ElapsedEventHandler( timer_Elapsed );
            timer.Stop( );

            ids.Id2 = 0;
            ids.Time2 = new DateTime( 2006 , 11 , 12 );

            //bw.RunWorkerAsync(ids);
            //bw.RunWorkerAsync(1740300);

            timer.Start( );
        }

        private void timer_Elapsed( object sender , ElapsedEventArgs e )
        {
            //throw new NotImplementedException();
            // Test1();
            // Test2();
            // Test3();
        }

        private void Test1( )
        {
            lock ( locker )
            {
                ids.Id1 = ids.Id2;
                ids.Id2 += 100;
            }
            if ( !bw.IsBusy )
            {
                bw.RunWorkerAsync( ids.Id2 );
            }
        }

        private void Test2( )
        {
            lock ( locker )
            {
                ids.Id1 = ids.Id2;
                ids.Id2 += 100;
            }
            if ( !bw.IsBusy )
            {
                bw.RunWorkerAsync( ids );
            }
        }

        private void Test3( )
        {
            lock ( locker )
            {
                ids.Id1 = ids.Id2;
                ids.Id2 += 100;
                ids.Time2 = DateTime.Today;
            }
            if ( !bw.IsBusy )
            {
                bw.RunWorkerAsync( ids );
            }
        }

        public void Set_AutoId( AutoIds _ids )
        {
            lock ( locker )
            {
                ids = _ids;
            }
        }

        private void bw_DoWork( object sender , DoWorkEventArgs e )
        {
            IsRunning = true;
            string connectString = DatabaseHelper.GetConnectString( );

            //AutoIds ids = new AutoIds(0, 0, new DateTime(2006, 12, 12), new DateTime(2006, 12, 12));
            if ( e.Argument.GetType( ) == typeof( Int32 ) || e.Argument.GetType( ) == typeof( int ) )
            {
                ids.Id2 = Convert.ToInt32( e.Argument );
            }
            else
            {
                ids = ( AutoIds )( e.Argument );
            }

            using ( DataContext context = new DataContext( connectString ) )
            {
                DateTime t1 = DateTime.Now;
                try
                {
                    context.Log = Console.Out;
                    context.CommandTimeout = 60;
                    Int32 autoId = ( Int32 )ids.Id2;// Convert.ToInt32(e.Argument);
                    result = context.ExecuteCommand( "delete ExcessRecord where AutoId <= {0}" , autoId );
                    /*
                    DateTime today = DateTime.Today;
                    TimeSpan span = new TimeSpan(366, 0, 0, 0);// 100 天的时间
                    if (today.Subtract(span).CompareTo(ids.Time2) >= 0)
                    {
                        result = context.ExecuteCommand("delete ExcessRecord where AutoId < {0}", autoId);
                    }
                    else
                    {
                        result =
                            context.ExecuteCommand(
                                "UPDATE ExcessRecord SET [SystemId] = 1 where AutoId <= {0} and AutoId >= {1}",
                                new object[] { ids.Id2, ids.Id1 });
                    }*/
                }
                catch ( SqlException ex )
                {
                    // //MyShowMessage.MySqlExceptionShow(ex, "!!!删除记录 error !!! ");
                }
                Console.Write( "delete count = " );
                Console.WriteLine( result );
                Console.Write( "耗时:" );
                Console.WriteLine( DateTime.Now.Subtract( t1 ).TotalSeconds.ToString( ) );
            }
            e.Result = result;    // 传递给 RunWorkerCopmleted
            IsRunning = false;
        }

        //void bw_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    string connectString = DatabaseHelper.GetConnectString();
        //    int result = 0;

        //    using (DataContext context = new DataContext(connectString))
        //    {
        //        DateTime t1 = DateTime.Now;
        //        try
        //        {
        //            context.Log = Console.Out;
        //            Int32 autoId = Convert.ToInt32(e.Argument);
        //            result = context.ExecuteCommand("delete ExcessRecord where AutoId <= {0}", autoId);

        //        }
        //        catch (SqlException ex)
        //        {
        //            //MyShowMessage.MySqlExceptionShow(ex, "!!!删除记录 error !!! ");
        //        }
        //        Console.Write("delete count = ");
        //        Console.WriteLine(result);
        //        Console.Write("耗时:");
        //        Console.WriteLine(DateTime.Now.Subtract(t1).TotalSeconds.ToString());
        //    }
        //    e.Result = result;    // 传递给 RunWorkerCopmleted
        //}

        //static void bw_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    string connectString = DatabaseHelper.GetConnectString();
        //    int result = 0;
        //    AutoIds ids = new AutoIds(0, 0, new DateTime(2006, 12, 12), new DateTime(2006, 12, 12));
        //    if (e.Argument.GetType() == typeof(UInt32) || e.Argument.GetType() == typeof(int))
        //    {
        //        ids.Id2 = Convert.ToUInt32(e.Argument);
        //    }
        //    else
        //    {
        //        ids = (AutoIds)(e.Argument);
        //    }
        //    using (DataContext context = new DataContext(connectString))
        //    {
        //        DateTime t1 = DateTime.Now;
        //        try
        //        {
        //            context.Log = Console.Out;
        //            UInt32 autoId = ids.Id2;// Convert.ToInt32(e.Argument);
        //            DateTime today = DateTime.Today;
        //            TimeSpan span = new TimeSpan(100, 0, 0, 0);// 100 天的时间

        //            if (today.Subtract(span).CompareTo(ids.Time2) >= 0)
        //            {
        //                result = context.ExecuteCommand("delete ExcessRecord where AutoId <= {0}", autoId);
        //            }
        //            else
        //            {
        //                result =
        //                    context.ExecuteCommand(
        //                        "UPDATE ExcessRecord SET [SystemId] = 1 where AutoId <= {0} and AutoId >= {1}",
        //                        new object[] { ids.Id2, ids.Id1 });
        //            }
        //        }
        //        catch (SqlException ex)
        //        {
        //            ////MyShowMessage.MySqlExceptionShow(ex, "!!!删除记录 error !!! ");
        //            Console.WriteLine(ex.Errors[0].Message);
        //        }
        //        Console.Write("delete count = ");
        //        Console.WriteLine(result);
        //        Console.Write("耗时:");
        //        Console.WriteLine(DateTime.Now.Subtract(t1).TotalSeconds.ToString());
        //    }
        //    e.Result = result;    // 传递给 RunWorkerCopmleted

        //    /* for (int i = 0; i <= 100; i += 20)
        //     {
        //         if (bw.CancellationPending)
        //         {
        //             e.Cancel = true;

        //             return;

        //         }

        //         bw.ReportProgress(i);

        //         Thread.Sleep(1000);

        //     }*/

        //    //e.Result = 123;    // 传递给 RunWorkerCopmleted

        //}

        //void bw_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    IsRunning = true;
        //    timer.Stop();
        //    AutoIds ids = new AutoIds(0, 0, new DateTime(2006, 12, 12), new DateTime(2006, 12, 12));
        //    DateTime today = DateTime.Today;
        //    TimeSpan span = new TimeSpan(100, 0, 0, 0);// 100 天的时间
        //    if (e.Argument.GetType() == 100.GetType())
        //    {
        //        ids.Id2 = Convert.ToUInt32(e.Argument);
        //    }
        //    else
        //    {
        //        ids = (AutoIds)(e.Argument);
        //    }

        //    string connectString = DatabaseHelper.GetConnectString();

        //    using (DataContext context = new DataContext(connectString))
        //    {
        //        DateTime t1 = DateTime.Now;
        //        try
        //        {
        //            context.Log = Console.Out;
        //            DateTime today = DateTime.Today;
        //            TimeSpan span = new TimeSpan(100, 0, 0, 0);// 100 天的时间

        //            if (today.Subtract(span).CompareTo(ids.Time2) >= 0)
        //            {
        //                result = context.ExecuteCommand("delete ExcessRecord where AutoId <= {0}", ids.Id2);

        //            }
        //            else
        //            {
        //                result =
        //                    context.ExecuteCommand(
        //                        "UPDATE ExcessRecord SET [SystemId] = 1 where AutoId <= {0} and AutoId >= {1}",
        //                        new object[] { ids.Id2, ids.Id1 });
        //            }

        //        }
        //        catch (SqlException ex)
        //        {
        //            //  //MyShowMessage.MySqlExceptionShow(ex, "!!!删除记录 error !!! ");
        //            Console.WriteLine(ex.Errors[0].Message);
        //        }
        //        StringBuilder sb = new StringBuilder();
        //        sb.Append("bw_DoWork ------      delete count = ");
        //        sb.AppendLine(result.ToString());
        //        sb.Append("bw_DoWork ------      耗时: ");
        //        sb.AppendLine(DateTime.Now.Subtract(t1).TotalSeconds.ToString());
        //        Console.WriteLine(sb.ToString());

        //    }

        //    e.Result = result;    // 传递给 RunWorkerCopmleted

        //    IsRunning = false;
        //    timer.Start();

        //}

        /*

         */

        private void bw_RunWorkerCompleted( object sender , RunWorkerCompletedEventArgs e )
        {
            if ( e.Cancelled )

                Console.WriteLine( "You cancelled!" );

            else if ( e.Error != null )

                Console.WriteLine( "Worker exception: " + e.Error.ToString( ) );

            else

                Console.WriteLine( "RunWorkerCompleted 删除记录 - " + e.Result );      // 从 DoWork
        }

        private void bw_ProgressChanged( object sender , ProgressChangedEventArgs e )
        {
            Console.WriteLine( "Reached " + e.ProgressPercentage + "%" );
        }
    }
}